<?php
defined('BASEPATH') or die('No direct script access allowed');
/**
 *
 * @生成验证码图片
 * Author lmx
 * create 2017-04-13 10:42
 */

Class Captcha{

    private $width;
    private $height;
    private $codeNum;
    private $code;
    private $im;

    function __construct($width = 80,$height = 30,$codeNum = 4)
    {
        $this -> width = $width;
        $this -> height = $height;
        $this -> codeNum = $codeNum;
    }

    public function showImg()
    {
        $this -> createImg();
        $this-> setDisturb();
        $this -> setCaptcha();
        $this -> outputImg();
    }

    public function getCaptcha(){
        $this -> createCode();
        return $this -> code;
    }

    private function createImg(){
        $this -> im = imagecreatetruecolor($this->width,$this->height);
        $bgColor = imagecolorallocate($this->im,200,200,200);
        imagefill($this -> im,0,0,$bgColor);
    }

    private function setDisturb()
    {
        $area = ($this->width * $this->height) / 20;
        $disturbNum = ($area > 250) ? 250 : $area;
        // add interference point
        for ($i = 0; $i < $disturbNum; $i++) {
            $color = imagecolorallocate($this->im, rand(0, 255), rand(0, 255), rand(0, 255));
            imagesetpixel($this->im, rand(1, $this->width - 2), rand(1, $this->height - 2), $color);
        }
        // add arc line
        for ($i = 0; $i < 5; $i++) {
            $color = imagecolorallocate($this->im, rand(0, 255), rand(0, 255), rand(0, 255));
            imagearc($this->im, rand(0, $this->width), rand(0, $this->height), rand(30, 300), rand(20, 200), 50, 30, $color);
        }
    }

    private function createCode(){
        $str = "0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ";
        for($i = 0;$i<$this ->codeNum;$i++){
            $this -> code .= $str{rand(0, strlen($str) - 1)};
        }
    }

    private function setCaptcha(){
        for($i = 0;$i<$this -> codeNum;$i++){
            $color = imagecolorallocate($this -> im,0,0,0);
            $size = rand(floor($this -> height/5),floor($this -> height / 3));
            $x = floor($this -> width / $this -> codeNum) * $i + 5;
            $y = rand(0,$this->height -20);
            imagechar($this->im,$size,$x,$y,$this -> code{$i},$color);
        }
    }

    private function outputImg(){
        if(imagetypes() &  IMG_JPG){
            header("Content-type:image/jpeg");
            imagejpeg($this->im);
        }else if(imagetypes() & IMG_PNG){
            header("Content-type:image/png");
            imagepng($this->im);
        }else if(imagetypes() & IMG_GIF){
            header("Content-type:image/gif");
            imagegif($this->im);
        }else{
            die("Don't support image type!");
        }
    }

}